package com.bbx.taxi.client.Activity.Order;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.animation.LayoutTransition;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.MeasureSpec;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;
import butterknife.InjectView;

import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.model.official.passanger.Official_AABuild;
import com.bbx.api.sdk.model.official.passanger.Return.Official_ORG;
import com.bbx.api.sdk.model.official.passanger.Return.Official_ORGChilds;
import com.bbx.api.sdk.model.official.passanger.Return.Official_OrgPath;
import com.bbx.api.sdk.model.official.passanger.Return.Official_ORGChilds.Childs;
import com.bbx.api.sdk.model.official.passanger.Return.Official_OrgPath.Path;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Adapter.AddOrganizationAdapter;
import com.bbx.taxi.client.Adapter.OrganizationAdapter;
import com.bbx.taxi.client.Bean.Extra.OrderMsg;
import com.bbx.taxi.client.Bean.Extra.OrganizationMsg;
import com.bbx.taxi.client.DB.Util.DBcolumns;
import com.bbx.taxi.client.Task.MyORGPathTask.OnOrgPathListener;
import com.bbx.taxi.client.Task.MyORGPathTask;
import com.bbx.taxi.client.Task.MyORGTask;
import com.bbx.taxi.client.Task.MyORGChildsTask;
import com.bbx.taxi.client.Task.MyORGTask.OnORGListener;
import com.bbx.taxi.client.Task.MyORGChildsTask.OnORGChildsListener;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.Util.MyDisplayMetrics;
import com.bbx.taxi.client.widget.MyTextView;
import com.bbx.taxi.client.widget.DropDown.DropDownMenu;
import com.bbx.taxi.client.widget.DropDown.DropDownMenu.OnShowStatusListener;
import com.bbx.taxi.client.widget.ScrollView.MyHorizontalScrollView;
import com.bbx.taxi.official.R;
import com.example.mylistview.pullListView.PullToRefreshLayout;
import com.example.mylistview.swipemenu.MyListView;
import com.example.mylistview.swipemenu.SwipeMenu;
import com.example.mylistview.swipemenu.MyListView.OnMenuItemClickListener;

/**
 * @Path com.bbx.taxi.client.Activity.Order.AddOrganization.java
 * @Author 严旭文
 * @Date 2016-3-30 下午2:29:40
 * @Company 蓝海（福建）信息技术有限公司
 * @Description 添加机构
 */
public class AddOrganization extends BaseBBXActivity implements OnORGListener,
		OnORGChildsListener, OnOrgPathListener {

	@InjectView(R.id.dropDownMenu)
	DropDownMenu mDropDownMenu;
	Button confirm;
	View contentView;
	private Button btn_add;
	private OrganizationAdapter mOrganizationAdapter;
	private AddOrganizationAdapter adapter_ju, adapter_bu, adapter_num;
	private LinearLayout layout_org;//机构组
	private MyHorizontalScrollView mMyHorizontalScrollView;//机构组
	public ListView lv_ju, lv_bu, lv_num;
	private List<Map<String, String>> list_organization = new ArrayList<Map<String, String>>();
	private List<Childs> list_ju, list_bu;
	
	//机构数组，但是不包括默认的第一级顶级机构跟第二级机构，
	private List<ListView> list_org_view=new ArrayList<ListView>();
	private List<AddOrganizationAdapter> list_org_adapter=new ArrayList<AddOrganizationAdapter>();
	/**第一级跟第二级不算的机构数组的数据*/
	private List<List<Childs>> list_org_data=new ArrayList<List<Childs>>();
	
	
	private List<String> list_num;
	/**默认机构数量，也就是说不可删除，不添加到list_org_view机构数组里面*/
	private int DEFAULT_ORG=2;
	private int LAYER_FIRST = 0;
	private int LAYER_SECOND = 1;
	/**层数从LAYER_SECOND接下去，则为2，3，4类推下去*/
	private List<Integer> LAYER=new ArrayList<Integer>();
	/**人数*/
	private int totalnum;
	private String jump_type = "";
	/** 所在的部门id */
	private String depart_id;
	/** 顶级机构id */
	private String root_org_id;
	/**机构路径，值存储机构id*/
	private List<String> path=new ArrayList<String>();
	/**屏幕宽度*/
	private int width=0;
	private LayoutInflater inflater;
	private String split="-";

	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_menu_myorder_officail);
		super.onCreate(savedInstanceState);
		width=(int) MyDisplayMetrics.getWidth(context);
		inflater=LayoutInflater.from(context);

	}

	@Override
	protected void initView() {
		setTitle2(true,getString(R.string.title_addorg), -1,getString(R.string.title_right_add));
		try {
			totalnum = Integer.parseInt(getIntent().getExtras().getString(
					OrganizationMsg.extra_num));
			jump_type = getIntent().getExtras().getString(
					OrganizationMsg.extra_type);
			root_org_id = getIntent().getExtras().getString(
					OrganizationMsg.extra_root_org_id);
			depart_id = getIntent().getExtras().getString(
					OrganizationMsg.extra_depart_id);
			list_organization = (List<Map<String, String>>) getIntent()
					.getSerializableExtra(OrganizationMsg.extra_list);

		} catch (Exception e) {
		}

		initDropDown();
		initListView();
	}

	@Override
	protected void initData() {
		// 获取用户的机构路径
		MyORGPathTask.getInstance(context, depart_id, 0).setOnOrgPathListener(
				this);
	}

	private void initDropDown() {   

		ArrayList<View> Views = new ArrayList<View>();
		View dropview = LayoutInflater.from(context).inflate(
				R.layout.drop_addorganization, null);
		btn_add = (Button) dropview.findViewById(R.id.btn_add);
		btn_add.setOnClickListener(this);

		lv_ju = (ListView) dropview.findViewById(R.id.lv_ju).findViewById(R.id.lv_org);
		lv_bu = (ListView) dropview.findViewById(R.id.lv_bu).findViewById(R.id.lv_org);
		lv_num = (ListView) dropview.findViewById(R.id.lv_num);
		layout_org=(LinearLayout)dropview.findViewById(R.id.layout_org);
		mMyHorizontalScrollView=(MyHorizontalScrollView)dropview.findViewById(R.id.horizontalscrollview);
		setViewWidth(lv_ju);
		setViewWidth(lv_bu);
		// 局
		list_ju = new ArrayList<Childs>();
		adapter_ju = new AddOrganizationAdapter(context,
				AddOrganizationAdapter.TYPE_JU, list_ju);
		lv_ju.setAdapter(adapter_ju);
		// 部
		list_bu = new ArrayList<Childs>();
		adapter_bu = new AddOrganizationAdapter(context,
				AddOrganizationAdapter.TYPE_BU, list_bu);
		lv_bu.setAdapter(adapter_bu);
		list_num = new ArrayList<String>();
		for (int i = 1; i <= totalnum; i++) {
			list_num.add(i + "");
		}
		adapter_num = new AddOrganizationAdapter(context, list_num);
		lv_num.setAdapter(adapter_num);

		Views.add(dropview);

		String headers[] = { "" };
		// init context view
		contentView = LayoutInflater.from(context).inflate(
				R.layout.activity_addorganization, null);
		contentView.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT));
		mDropDownMenu.setDropDownMenu(Arrays.asList(headers), Views,
				contentView);
		mDropDownMenu.setmOnShowStatusListener(new OnShowStatusListener() {
			
			@Override
			public void onShowStatus(boolean isShow) {
				if(isShow){
					setTitle2(true,getString(R.string.title_addorg), -1,getString(R.string.title_right_cancel));
				}else{
					setTitle2(true,getString(R.string.title_addorg), -1,getString(R.string.title_right_add));
				}
				
			}
		});
		confirm = (Button) contentView.findViewById(R.id.confirm);
		confirm.setOnClickListener(this);
		lv_ju.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				for (int i = 0; i < list_ju.size(); i++) {
					if (i == position) {
						adapter_ju.isSelected.put(i, true);
					} else {
						adapter_ju.isSelected.put(i, false);
					}
				}
				adapter_ju.notifyDataSetChanged();
				lv_bu.setLayoutTransition(getLayoutTransition());
				removeAllViews(false,LAYER_SECOND+1);
				getORGChilds(list_ju.get(position).getId(),LAYER_SECOND,false);
			}
		});
		lv_bu.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (position == adapter_bu.getSelectedId()) {
					adapter_bu.isSelected.put(position, false);
					removeAllViews(false,LAYER_SECOND+1);
				} else {
					for (int i = 0; i < list_bu.size(); i++) {
						if (i == position) {
							adapter_bu.isSelected.put(i, true);
						} else {
							adapter_bu.isSelected.put(i, false);
						}
					}
					getORGChilds(list_bu.get(position).getId(),LAYER_SECOND+1,false);
				}
				lv_bu.setLayoutTransition(null);
 				adapter_bu.notifyDataSetChanged();
 				
			}
		});
		lv_num.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				for (int i = 0; i < list_num.size(); i++) {
					if (i == position) {
						adapter_num.isSelected.put(i, true);
					} else {
						adapter_num.isSelected.put(i, false);
					}
				}
				adapter_num.notifyDataSetChanged(position);
			}
		});

	}
	/**
	 * 机构数组的点击事件
	 */
	public void setListOrgItemClick(){
		for(int i=0;i<LAYER.size();i++){
			final int id=i;
			final ListView listview=list_org_view.get(id);
			final AddOrganizationAdapter adapter=list_org_adapter.get(id);
			final List<Childs> list_childs=list_org_data.get(id);
			final int layer=LAYER.get(id);
			listview.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					if (position == adapter.getSelectedId()) {
						adapter.isSelected.put(position, false);
						removeAllViews(false,layer+1);
					} else {
						for (int i = 0; i < list_childs.size(); i++) {
							if (i == position) {
								adapter.isSelected.put(i, true);
							} else {
								adapter.isSelected.put(i, false);
							}
						}
						getORGChilds(list_childs.get(position).getId(),layer+1,false);
					}
					listview.setLayoutTransition(null);
					listview.setAdapter(adapter);
					
				}
			});
		}
	}

	public void initListView() {
		mMyListView = (MyListView) contentView.findViewById(R.id.MyListView);
		pullToRefreshLayout = (PullToRefreshLayout) contentView
				.findViewById(R.id.pullToRefreshLayout);
		if (list_organization == null) {
			list_organization = new ArrayList<Map<String, String>>();
		}
		mOrganizationAdapter = new OrganizationAdapter(context,
				list_organization);
		mMyListView.setAdapter(mOrganizationAdapter);
		notifyDataSetChanged(mOrganizationAdapter);
		mMyListView.hideLoad();
		mMyListView.hideRefresh();
		LinearLayout layout_nodata = (LinearLayout) contentView
				.findViewById(R.id.layout_nodata);
		mMyListView.setEmptyView(layout_nodata);
		initswipe();
	}

	/**
	 * 初始化ListView的Item菜单
	 */
	public void initswipe() {
		super.initswipe();
		// step 2. listener item click event
		mMyListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public void onMenuItemClick(final int position, SwipeMenu menu,
					int index) {
				// ApplicationInfo item = mAppList.get(position);
				switch (index) {
				case 0:
					list_organization.remove(position);
					notifyDataSetChanged(mOrganizationAdapter);
					Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							mMyListView.closeMenu();
						}
					}, 200);
					break;

				}
			}
		});

	}

	private void notifyDataSetChanged(BaseAdapter adapter) {
		adapter.notifyDataSetChanged();
		if (adapter.getCount() <= 0) {
			confirm.setVisibility(View.GONE);
		} else {
			confirm.setVisibility(View.VISIBLE);
		}

	}
	/**
	 * 设置View的大小
	 */
	public void setViewWidth(View v){
		RelativeLayout.LayoutParams linearParams =(RelativeLayout.LayoutParams) v.getLayoutParams();
		linearParams.width=(width/3);
		v.setLayoutParams(linearParams);
	}
	/**
	 *获取子机构
	 */
	private void getORGChilds(String org_id,int LAYER,boolean automatic){
		MyORGChildsTask.getInstance(context, org_id, LAYER,automatic).setOnORGChildsListener(this);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_left:
			onfinish();
			break;
		case R.id.tv_right2:
			if(tv_right2.getText().toString().equals(context.getString(R.string.title_right_add))){
			btn_add.setEnabled(true);
			list_num.clear();
			int mtotalnum=0;
			mtotalnum=totalnum-onAlreadyAddedNum();
			if(mtotalnum>0){
			for (int i = 1; i <= mtotalnum; i++) {
				list_num.add(i + "");
			 }
			adapter_num.notifyDataSetChanged(0);
			mDropDownMenu.openMenu();
			setOnCloseSwipeLayout(true);
			new Handler().postDelayed(new Runnable() {
				
				@Override
				public void run() {
					mMyHorizontalScrollView.fullScroll(HorizontalScrollView.FOCUS_RIGHT);//滚动到底部
				}
			}, 500);
			

			}else{
				ToastUtil.showToast(context, "已达到该车型的最大人数限制");
			}
			}else{
				mDropDownMenu.closeMenu();
				setOnCloseSwipeLayout(false);
				
			}
			
			break;
		case R.id.btn_add:
			String ju = (list_ju != null && !list_ju.isEmpty() && adapter_ju
			        .getSelectedId() >= 0) ? list_ju.get(
			         adapter_ju.getSelectedId()).getName() : "";
	        String ju_id = (list_ju != null && !list_ju.isEmpty() && adapter_ju
			        .getSelectedId() >= 0) ? list_ju.get(
			        adapter_ju.getSelectedId()).getId() : "";
	        String bu = (list_bu != null && !list_bu.isEmpty() && adapter_bu
			        .getSelectedId() >= 0) ? list_bu.get(
			        adapter_bu.getSelectedId()).getName() : "";
	        String bu_id = (list_bu != null && !list_bu.isEmpty() && adapter_bu
			        .getSelectedId() >= 0) ? list_bu.get(
			        adapter_bu.getSelectedId()).getId() : "";
	        String num = (list_num != null && !list_num.isEmpty() && adapter_num
			       .getSelectedId() >= 0) ? list_num.get(adapter_num
			       .getSelectedId()) : "0";
			
			int id=-1;
			String org_id="";
			String org_name="";
			if(ju_id!=null&&!ju_id.equals("")){
				org_id=ju_id;
			}
			if(bu_id!=null&&!bu_id.equals("")){
				org_id=bu_id;
			}
			if(ju!=null&&!ju.equals("")){
				org_name=ju;
			}
			if(bu!=null&&!bu.equals("")){
				org_name+=split+bu;
			}
			
			for(int i=list_org_adapter.size()-1;i>=0;i--){
				if(list_org_adapter.get(i).getSelectedId()!=-1){
					id=i;
					org_id=list_org_data.get(i).get(list_org_adapter.get(i).getSelectedId()).getId();
					break;
				}
			}
			for(int i=0;i<=id;i++){
				org_name+=split+list_org_data.get(i).get(list_org_adapter.get(i).getSelectedId()).getName();
			}
			
			
			for (int i = 0; i < list_organization.size(); i++) {
				if (list_organization.get(i).get(OrganizationAdapter.ORG_ID).equals(org_id)) {
					//已经添加过该机构
					onAlreadyAdded(i,num);
					return;
				} 
			}
			
			int numble=onAlreadyAddedNum();
			if (numble + Integer.parseInt(num) > totalnum) {
				ToastUtil.showToast(context, "人数已经超过了");
				return;
			}
			btn_add.setEnabled(false);
			mDropDownMenu.closeMenu();
			Map<String, String> map = new HashMap<String, String>();
			map.put(OrganizationAdapter.ORG_ID, org_id);
			map.put(OrganizationAdapter.ORG_NAME,org_name);
			map.put(OrganizationAdapter.ORG_NUM,num+"");
			list_organization.add(map);
			notifyDataSetChanged(mOrganizationAdapter);

			break;
		case R.id.confirm:
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putString(OrganizationMsg.extra_type, jump_type);
			intent.putExtras(bundle);
			intent.putExtra(OrganizationMsg.extra_list,
					(Serializable) list_organization);
			setResult(resultCode, intent);
			finish();
			break;
		}
	}
	/**
	 * 已经添加该部门
	 */
	public void onAlreadyAdded(int i,String num){
		//已经添加过该机构
		Map<String, String> map=new HashMap<String, String>();
		map.put(OrganizationAdapter.ORG_ID,list_organization.get(i).get(OrganizationAdapter.ORG_ID));
		map.put(OrganizationAdapter.ORG_NAME, list_organization.get(i).get(OrganizationAdapter.ORG_NAME));
		int count=Integer.parseInt(list_organization.get(i).get(OrganizationAdapter.ORG_NUM));
		map.put(OrganizationAdapter.ORG_NUM,String.valueOf(count+Integer.parseInt(num)));
		list_organization.set(i, map);
		notifyDataSetChanged(mOrganizationAdapter);
		mDropDownMenu.closeMenu();
	}
	/**
	 * 返回已经添加多少人了
	 */
	public int onAlreadyAddedNum(){
		int numble = 0;
		for (int i = 0; i < list_organization.size(); i++) {
			numble = numble
					+ Integer.parseInt(list_organization.get(i).get(
							OrganizationAdapter.ORG_NUM));
		}
		return numble;
	}
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			onfinish();
			return true;

		}
		return false;
	}
	@Override
	public void onfinish() {
		if(tv_right2.getText().toString().equals(context.getString(R.string.title_right_add))){
			if(list_organization==null||list_organization.isEmpty()){
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putString(OrganizationMsg.extra_type, jump_type);
				intent.putExtras(bundle);
				intent.putExtra(OrganizationMsg.extra_list,
						(Serializable) list_organization);
				setResult(resultCode, intent);
			}else{
				
			}
			
			super.onfinish();
		}else{
			mDropDownMenu.closeMenu();
			setOnCloseSwipeLayout(false);
		}
		
	}
    /**
     * 移除机构数组，
     * isAll为true的时候移除全部试图，并移除所有数据
     *     为false的时候,根据传递的层数，获取该试图id，并且移除
     */
    public void removeAllViews(boolean isAll,int Layer){
    	if(isAll){
    		layout_org.removeViews(DEFAULT_ORG, LAYER.size());
    		list_org_view.clear();
    		list_org_adapter.clear();
    		list_org_data.clear();
    		LAYER.clear();
    	}else{
    		int id=-1;
    		int count=0;
    		for(int i=0;i<LAYER.size();i++){
    			if(Layer==LAYER.get(i)){
    				id=i;
    				count=LAYER.size()-i;
    				break;
    			}
    		}
    		if(id!=-1){
    		for(int i=list_org_view.size()-1;i>=id;i--){
    			list_org_view.remove(i);
    		}
    		for(int i=list_org_adapter.size()-1;i>=id;i--){
    			list_org_adapter.remove(i);
    		}
    		for(int i=list_org_data.size()-1;i>=id;i--){
    			list_org_data.remove(i);
    		}
    		for(int i=LAYER.size()-1;i>=id;i--){
    			LAYER.remove(i);
    		}
    		Log.e("",LAYER+"//////////"+Layer);
    		layout_org.removeViews(Layer, count);
    		}
    	}
    	setListOrgItemClick();
    }
    /**
     * 添加子机构
     */
    public void addViews(List<Childs> list,boolean automatic){
		List<Childs> list_childs=new ArrayList<Childs>();
		AddOrganizationAdapter org_adapter;
		int Selected = -1;
    	
		View view=(View)inflater.inflate(R.layout.listview_org,null); 
		ListView lv_org=(ListView)view.findViewById(R.id.lv_org);
		setViewWidth(lv_org);
		layout_org.addView(view,DEFAULT_ORG+list_org_view.size());
		LAYER.add(DEFAULT_ORG+list_org_view.size());
		list_org_view.add(lv_org);
		new Handler().postDelayed(new Runnable() {
			
			@Override
			public void run() {
				mMyHorizontalScrollView.fullScroll(HorizontalScrollView.FOCUS_RIGHT);//滚动到底部
			}
		}, 500);

		 list_childs=list;
		 list_org_data.add(list_childs);
	
		 if(automatic)
			for (int i = 0; i < list_childs.size(); i++) {
				// 判断所在的部门是否在子机构
				if (path.contains(list_childs.get(i).getId())) {
					Selected = i;
					getORGChilds(list_childs.get(Selected).getId(),LAYER.get(LAYER.size()-1)+1,true);
					break;
				}
			}
		 org_adapter = new AddOrganizationAdapter(context,
					AddOrganizationAdapter.TYPE_BU, list_childs);
		 list_org_adapter.add(org_adapter);
		 list_org_view.get(list_org_view.size()-1).setAdapter(org_adapter);
		 setListOrgItemClick();
		//如果所在部门在改机构，则选中
		  if(Selected>=0&&automatic){
			  org_adapter.notifyDataSetChanged(Selected);
			  list_org_view.get(list_org_view.size()-1).setSelection(Selected);
		  }
		 
	
    }
	@Override
	public void onORGChildsFinish(Official_ORGChilds mOfficial_ORGChilds, int layer,boolean automatic) {
		/** 默认的选择项 */
		int defaultRootSelected = -1;
		int defaultDepartSelected = -1;
		if (mOfficial_ORGChilds != null) {
			List<Childs> list = mOfficial_ORGChilds.getList();
			// 获取的是第一层【局】
			if (layer == LAYER_FIRST) {
				list_ju.clear();
				list_ju.addAll(list);
                if(automatic)
				for (int i = 0; i < list_ju.size(); i++) {
					// 判断所在的部门是否在顶级机构
					if (path.contains(list_ju.get(i).getId())) {
						defaultRootSelected = i;
						getORGChilds(list_ju.get(defaultRootSelected).getId(),LAYER_SECOND,true);
						break;
					}
				}
				//如果所在部门在改机构，则选中
				if(defaultRootSelected>=0&&automatic){
					adapter_ju.notifyDataSetChanged(defaultRootSelected);
					lv_ju.setSelection(defaultRootSelected);
				}else{
					adapter_ju.notifyDataSetChanged();
				}
				if(!automatic){
					removeAllViews(true,0);
				}
				
			}
			// 获取第二层【部】
			else if (layer == LAYER_SECOND) {
				list_bu.clear();
				list_bu.addAll(list);
				
				if(automatic)
				for (int i = 0; i < list_bu.size(); i++) {
					// 判断所在的部门是否在子机构
					if (path.contains(list_bu.get(i).getId())) {
						defaultDepartSelected = i;
						getORGChilds(list_bu.get(defaultDepartSelected).getId(),LAYER_SECOND+1,true);
						break;
					}
				}
				//如果所在部门在改机构，则选中
				if(defaultDepartSelected>=0&&automatic){
					adapter_bu.notifyDataSetChanged(defaultDepartSelected);
					lv_bu.setSelection(defaultDepartSelected);
				}else{
					adapter_bu.notifyDataSetChanged(-1);
				}
				if(!automatic){
					removeAllViews(true,0);
				}
				
			}
			//第二层以后
			else {
				//没有数据则,判断是自动还是手动，手动的话则移除后面的ListView
				if(list==null||list.isEmpty()){
					if(!automatic){
						removeAllViews(false,layer);
					}
					return;
				}
				//先判断是否有这个数据，没有则添加，有则修改
				if(LAYER!=null&&!LAYER.isEmpty()&&LAYER.contains(layer)){
				for(int z=0;z<LAYER.size();z++){
					if(layer==LAYER.get(z)){
						int Selected = -1;
						AddOrganizationAdapter org_adapter;
						ListView listview_org=list_org_view.get(z);
						List<Childs> list_childs=new ArrayList<Childs>();
							list_childs=list_org_data.get(z);
							list_childs.clear();
							list_childs.addAll(list);
							list_org_data.set(z,list_childs);
							org_adapter = new AddOrganizationAdapter(context,
										AddOrganizationAdapter.TYPE_BU, list_childs);
							if(automatic)
							for (int i = 0; i < list_childs.size(); i++) {
								// 判断所在的部门是否在子机构
								if (path.contains(list_childs.get(i).getId())) {
									Selected = i;
									getORGChilds(list_childs.get(Selected).getId(),LAYER.get(z)+1,true);
									break;
								}
							}
							listview_org.setLayoutTransition(getLayoutTransition());
							listview_org.setAdapter(org_adapter);
							//如果所在部门在改机构，则选中
						  if(Selected>=0&&automatic){
							  org_adapter.notifyDataSetChanged(Selected);
							  listview_org.setSelection(Selected);
						  }
						  setListOrgItemClick();
						  if(!automatic){
							  //移除后面的数据
								removeAllViews(false,layer+1);
							}
						break;
					}
				  }
				}else{
					  addViews(list,automatic);
				  }	
			}

		}

	}

	@Override
	public void onOrgPathFinish(Official_OrgPath mOfficial_OrgPath) {
		if (mOfficial_OrgPath != null && mOfficial_OrgPath.getList() != null) {
			for(int i=0;i<mOfficial_OrgPath.getList().size();i++){
				path.add(mOfficial_OrgPath.getList().get(i).getId());
			}
		}
		if (root_org_id != null && !root_org_id.equals("")) {
			getORGChilds(root_org_id,LAYER_FIRST,true);
		} else {
			MyORGTask.getInstance(context, mApplication.getUid())
					.setOnORGListener(this);
		}

	}

	@Override
	public void onORGFinish(Official_ORG mOfficial_ORG) {
		root_org_id = mOfficial_ORG.getRoot_org_id();
		getORGChilds(root_org_id,LAYER_FIRST,true);

	}
	public LayoutTransition getLayoutTransition(){
		LayoutTransition transition = new LayoutTransition();
		transition.setAnimator(LayoutTransition.CHANGE_APPEARING,
				transition.getAnimator(LayoutTransition.CHANGE_APPEARING));
		transition.setAnimator(LayoutTransition.APPEARING,
				transition.getAnimator(LayoutTransition.APPEARING));
		transition.setAnimator(LayoutTransition.DISAPPEARING,
				transition.getAnimator(LayoutTransition.DISAPPEARING));
		transition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING,
				transition.getAnimator(LayoutTransition.CHANGE_DISAPPEARING));
		return transition;
	}

}
